import json
from django.core.paginator import  Paginator
from django.http import *
from django.shortcuts import render

from department.models import Department
from user.models import User
from .models import WorkReport
from .models import ReportDraft


# Create your views here.
def get_draft(request):

    if request.method =='GET':
        user = request.session['user']
        values = ReportDraft.objects.filter(user=user)
        datas = []
        for value in values:
            if value:
                draft_dict = {}

                draft_dict['id'] = value.id
                draft_dict['title'] = value.title
                datas.append(draft_dict)
            else:
                JsonResponse({'code':10103})
        return JsonResponse({"code":200,'data':datas})
    elif request.method == 'POST':
        #获取下拉菜单的title 和id
        json_str = request.body
        #判断是否为空
        if not json_str:
            return JsonResponse({'code':10104})
        obj_str = json.loads(json_str)
        id = obj_str['id']
        title = obj_str['title']
        report = ReportDraft.objects.get(id=id,title=title)
        return JsonResponse({'code':200,'data':{"title":report.title,'report':report.report}})

def get_report(request):
    '''
    查看报告
    :param request:
    :return:
    '''
    # 收到前端发来的请求
    # 需返回数据给前端
    # 获取查询字符串content中的title
    title = request.GET.get('content')
    user = request.session['user']
    # 使用title在数据库中查找相同的内容
    data = WorkReport.objects.get(title=title)

    title = data.title
    report = data.report
    getdata = {'code':200,'title':title ,'report': report}
    return JsonResponse(getdata)

def save_draft(request):

    # 获取文本框内容
    json_str = request.body

    py_obj = json.loads(json_str)
    
    title = py_obj["title"]
    report = py_obj["report"]
    # 判断是否是空,如果是空则刷新页面>后面改页面代码-->如果是空则不发送请求内容
    if not py_obj:
        return render(request, 'workreport/addReport.html')

   
    # 向数据库添加内容   ---页面需要添加成功的提示
    # 后面需要修改: 从sesion中 获取 员工姓名 权限  部门
    # 部门
    user = User.objects.get(id=request.session['user'].id)
    ReportDraft.objects.create(title=title, report=report, user=user)

    return JsonResponse({'code': 200})

def add_work_report(request):
    if request.method=='GET':
        return render(request,'workreport/addReport.html')
    elif request.method=='POST':
        #获取文本框内容
        json_str = request.body
        py_obj = json.loads(json_str)
        report = py_obj['report']
        title = py_obj['title']
        #判断是否是空,如果是空则刷新页面>后面改页面代码-->如果是空则不发送请求内容
        if not py_obj:
          return render(request, 'workreport/addReport.html')
        #向数据库添加内容   ---页面需要添加成功的提示
        #后面需要修改: 从sesion中 获取 员工姓名 权限  部门
        #部门
        
        try:
            WorkReport.objects.get(title=title)
            return JsonResponse({"code": 10100, 'error': '已有相同标题'})
        except:
            department = Department.objects.get(title=request.session["user.department"].title)
            #员工姓名 id
            user = User.objects.get(id = request.session['user'].id)
            WorkReport.objects.create(title = title ,report=report,user=user,department=department)
            #添加成功后跳转到查询页面(暂定) 后期改为网页切换标签
            return JsonResponse({'code': 200})




def select_report(request):

     return render(request,'workreport/selectReport.html')


def del_report(request):
    url_report = request.POST['title']
    if not url_report:
        return HttpResponse('删除失败')
    report = WorkReport.objects.get(report=url_report)
    report.delete()
    return HttpResponse('删除成功')




def portpage_view(request):
    # 用户点击查看报告,获取数据所有数据加载发送至服务器
    # 需要获取sesion中的用户名
    # 获取用户的cookie,取出和cookie相同的sision
    # value = request.COOKIES.get('user_name')
    search = request.GET.get('search')

    if not search:
        data = WorkReport.objects.filter()
    else:
        data=WorkReport.objects.filter(title__contains=search)

    # 1.处理数据,将数据处理成Json接送格式
    dates = []
    # 处理数据库保存到列表中
    for value in data:

        dic = {}
        # dates[-1]['id'].get(dates[-1]['id']+1,0)
        dic['uid'] = value.user.id
        dic['user_name'] = value.user.user_name
        dic['department'] = value.department.title
        dic['title'] = value.title
        dic["created_time"] = value.created_time
        dic["updated_time"] = value.updated_time
        dates.append(dic)

    # 获取页面表单分页信息
    page = request.GET.get('page')
    limit = request.GET.get('limit')
    paginator = Paginator(dates, limit)
    pages = paginator.page(page)
    work_report = [x for x in pages]
    reports = {"code": 0, "msg": "", "count": data.count(), "data": work_report}
    return JsonResponse(reports)


def see_report(request):

    return render(request, 'workreport/queryReport.html')


def testlayer(request):
    return render(request,'workreport/testlayer.html')

def transfer_view(request):
    return render(request,'workreport/transfer.html')


